package com.study.newjava8.forkjoin;

import org.junit.Test;

import java.util.concurrent.RecursiveTask;

/**
 * 使用Fork/Join框架
 * RecursiveAction 里面的方法没有返回值
 * RecursiveTask有返回值
 */
public class ForkJoinText extends RecursiveTask<Long> {
    private long start;
    private long end;

    public ForkJoinText(long start, long end) {
        this.start = start;
        this.end = end;
    }


    /**
     * 拆分的临界值
     */
    private static final long THRESHOLD = 10000;

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THRESHOLD) {
            long sum = 0;
            for (long i = start; i <=end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;
            ForkJoinText left = new ForkJoinText(start, middle);
            //拆分子任务，同时压入线程队列
            left.fork();
            ForkJoinText right = new ForkJoinText(middle + 1, end);
            right.fork();
            return left.join() + right.join();
        }
    }

}
